package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.dto.User;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.security.service.UserInfo;
import com.cpit.qualitycontrol.dao.DeviceRepository;
import com.cpit.qualitycontrol.dao.SubTaskCrudRepository;
import com.cpit.qualitycontrol.dao.WorkOrderCrudRepository;
import com.cpit.qualitycontrol.dao.jpqlquery.DeviceQueryRepository;
import com.cpit.qualitycontrol.entity.Device;
import com.cpit.qualitycontrol.entity.SubTask;
import com.cpit.qualitycontrol.entity.UserToProductLine;
import com.cpit.qualitycontrol.entity.WorkOrder;
import com.cpit.qualitycontrol.service.DeviceService;
import com.cpit.qualitycontrol.service.UserToProductLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl implements DeviceService {

    private final String loggerName = this.getClass().getName();

    @Autowired
    private DeviceRepository rep = null;
    @Autowired
    private SubTaskCrudRepository subTaskCrudRepository;

    @Autowired
    private WorkOrderCrudRepository workOrderCrudRepository;
    @Autowired
    private DeviceQueryRepository deviceQueryRepository;

    @Autowired
    private UserToProductLineService userToProductLineService;

    @Override
    public Device findById(String id) {
        return deviceQueryRepository.findById(id);
    }

    @Override
    public List<Device> findAll() {
        Long productLineId = null;
        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            productLineId = new Long((long) list.get(0).getProductLineId());
        }

        return this.deviceQueryRepository.findByCondition(productLineId, null, null, null, null);
    }

    @Override
    public List<Device> findByCondition(int page,
                                        int size,
                                        String order,
                                        String orderBy,
                                        Long productLineId, String projectName, Long deviceTypeId, String deviceNum,
                                        String addrs) {
        if (orderBy == null || orderBy.length() == 0) {
            orderBy = "id";
        }
        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            productLineId = new Long((long) list.get(0).getProductLineId());
        }
        return deviceQueryRepository.findByCondition(productLineId, projectName, deviceTypeId, deviceNum, addrs, request).getContent();

    }

    @Override
    public List<Device> findByCondition(int page, int size, String order, String orderBy, String pattern) {
        if (orderBy == null || orderBy.length() == 0) {
            orderBy = "id";
        }
        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
        Page<Device> pg = null;
        if (pattern == null || pattern.equals(""))
            pg = this.rep.findAll(request);
        else
            pg = this.rep.findByNameContaining(pattern, request);
        return pg.getContent();
    }

    @Override
    public Device create(Device device) throws Exception {
        if (device == null)
            throw new Exception("参数为空");
        if (device.getId() != null && !device.getId().equals("")) {
            LogOperator.info(loggerName, "设备ID已赋值");
            if (rep.findById(device.getId()) != null)
                throw new Exception("相同编号设备已存在:" + device.getId());
        }
        Device dt = rep.findByName(device.getName());
        if (dt != null)
            throw new Exception("同名设备已存在:" + device.getName());
        return this.rep.save(device);
    }

    @Override
    public Device modify(Device device) throws Exception {
        if (device == null)
            throw new Exception("参数为空");
        Device dt = rep.findById(device.getId());
        if (dt == null)
            throw new Exception("修改的设备不存在:" + device);
        dt = rep.findByName(device.getName());
        if (dt != null && !dt.getId().equals(device.getId()))
            throw new Exception("同名设备已存在:" + device.getName());
        return this.rep.save(device);
    }


    public void delete(Device device) throws Exception {
        if (device == null)
            throw new Exception("参数为空");
        Device dt = rep.findById(device.getId());
        if (dt == null)
            throw new Exception("删除的设备不存在:" + device);
        /*检查删除的device是否存在子对象 Subtask Workorder*/
        List<SubTask> subTaskList = subTaskCrudRepository.findByDeviceId(device.getId());
        if (subTaskList != null && subTaskList.size() > 0) {
            throw new Exception("删除的设备存在子对象SubTask, 不能删除:" + device);
        }
        List<WorkOrder> workdOrderList = workOrderCrudRepository.findByDeviceId(device.getId());
        if (workdOrderList != null && workdOrderList.size() > 0) {
            throw new Exception("删除的设备存在子对象WorkOrder, 不能删除:" + device);
        }
        this.rep.delete(device.getId());
    }

    @Override
    public TableJsonData findByConditionJqg(TableDataQueryCondition cond) {
        PageRequest request = ServiceUtils.getPageRequestByTableDataQueryCondition(cond);

        Map queryCondMap = cond.getQueryCond();
        String projectName = (String) queryCondMap.get("projectName");
        Long productLineId = null;
        String strPLid = (String) queryCondMap.get("productLineId");
        if (strPLid != null && !((strPLid).equals(""))) {
            productLineId = Long.valueOf(strPLid);
        }
        List<UserToProductLine> list = userToProductLineService.findByUserId(getLoginUser().getId());
        if (list != null && list.size() > 0) {//产品线角色
            productLineId = new Long((long) list.get(0).getProductLineId());
        }

        Long deviceTypeId = null;
        String strDeviceTypeId = (String) queryCondMap.get("deviceTypeId");
        if (strDeviceTypeId != null && (!strDeviceTypeId.equals(""))) {
            deviceTypeId = Long.valueOf(strDeviceTypeId);
        }

        String addrs = (String) queryCondMap.get("addrs");
        String deviceNum = (String) queryCondMap.get("id");
        Page<Device> ret = this.deviceQueryRepository.findByCondition(productLineId, projectName, deviceTypeId, deviceNum, addrs, request);

        return new TableJsonData(cond, ret.getTotalElements(), ret.getContent());
    }

    @Override
    public Device updateCoordinate(String id, Double longitude, Double Latitude) {
        Device device = rep.findById(id);
        device.setLongitude(longitude);
        device.setLatitude(Latitude);
        return rep.save(device);
    }

    /**
     * 获取登录用户信息
     *
     * @return
     */
    private User getLoginUser() {
        return ((UserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal()).getUser();
    }

}
